package unittest;

import tester.ExeRunner;

import java.io.*;

import junit.framework.TestCase;

/**
 * Created by IntelliJ IDEA.
 * User: aleck
 * Date: 2007-10-28
 * Time: 10:11:58
 * To change this template use File | Settings | File Templates.
 */
public class RunnerTest extends TestCase {
  public void testCmd() throws IOException {
    ExeRunner.executeNoIO(null, 10 * 1000, null,
        "cmd", "/c unittest\\stream.exe <unittest\\tin.txt >unittest\\tout.txt");
//    ExeRunner.execute(null, 10 * 1000, null,
//        "stream.exe", "<tin.txt", ">tout.txt");
//    ExeRunner.execute(null, 10 * 1000, null,
//        "unittest\\stream.exe", "<unittest\\tin.txt", ">unittest\\tout.txt");
  }

  public void testProcess() throws IOException {
//    ProcessBuilder pb = new ProcessBuilder("unittest\\stream.exe");
//    Process process = pb.start();
    Process process = Runtime.getRuntime().exec("unittest\\stream.exe");
    OutputStream os = process.getOutputStream();
    OutputStreamWriter osw = new OutputStreamWriter(os);
    String line;
//    BufferedReader br = new BufferedReader(
//        new FileReader("unittest\\article6.in"));
//    line = br.readLine();
//    while (line != null) {
//      osw.write(line + '\n');
//      line = br.readLine();
//    }
//    osw.flush();
    ExeRunner.transferStream(new FileInputStream("unittest\\article6.in"), os);
    os.flush();
    InputStream is = process.getInputStream();
    OutputStream fos = new FileOutputStream("unittest\\fos.txt");
    byte[] b = new byte[1024];
    int len;
    long timeToExit = System.currentTimeMillis() + 10 * 1000;
    while (!isProcessAlive(process)) {
      if (is.available() > 0) {
        len = is.read(b);
        fos.write(b, 0, len);
      }
      if (System.currentTimeMillis() >= timeToExit) {
        System.out.println("TIMEOUT");
        break;
      }
    }
    System.out.println("-- FINISHED --");
//    BufferedReader out = new BufferedReader(
//        new InputStreamReader(process.getInputStream()));
//    line = out.readLine();
//    while (line != null) {
//      System.out.println(line);
//      line = out.readLine();
//    }
    System.out.println("-- OK --");
  }

  private boolean isProcessAlive(Process process) {
    try {
      process.exitValue();
    } catch (IllegalThreadStateException e) {
      return false;
    }
    return true;
  }
}
